<template>
  <div
    style="
      display: grid;
      gap: 24px;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    "
  >
    <div class="card-content" @click="handleContent()">
      <el-card>
        <div
          style="
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            flex-direction: column;
          "
        >
          <i
            class="el-icon-circle-plus-outline"
            style="font-size: 60px; padding: 20px"
          ></i>
          <div>新建</div>
        </div>
      </el-card>
    </div>

    <div v-for="(item, key) in list" :key="key" class="card-content">
      <el-card style="display: flex; flex-direction: column">
        <div style="height: 100%; display: flex; flex-direction: column">
          <el-image :src="item.image" style="flex: 1"></el-image>
          <div style="font-size: 16px; margin: 12px 0 20px">
            <h4>{{ item.title }}</h4>
          </div>
          <div style="display: flex; justify-content: space-between">
            <div style="font-size: 12px" class="scrollable-content">
              <p>{{ replaceHtml(item.content) }}</p>
            </div>
          </div>
          <div style="padding-right: 12px">
            <el-button
              type="text"
              size="medium"
              @click="handleContent(item, true)"
              >编辑</el-button
            >
            <el-button type="text" size="medium" @click="delContent(item)"
              >删除</el-button
            >
          </div>
        </div>
      </el-card>
    </div>

    <el-dialog
      title="内容填写"
      :visible.sync="dialog_visible"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        :model="form"
        ref="ruleForm"
        label-width="80px"
        :rules="rules"
        style="padding-right: 40px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="展示" prop="image">
          <Upload
            @upload="handleFileUpload"
            accept=".jpg,.png,.jpeg"
            :imageUrl="form.image"
          >
            <el-button
              v-show="form.image"
              @click.stop="deleteImg"
              type="text"
              style="position: absolute; right: -10px; top: -10px; padding: 0"
              ><i class="el-icon-circle-close"></i></el-button
          ></Upload>
        </el-form-item>
        <el-form-item label="内容视频" prop="video">
          <Upload
            @upload="handleFileUploadVideo"
            accept=".mp4,.mov"
            :imageUrl="form.video"
          >
            <el-button
              v-show="form.video"
              @click.stop="deleteVideo"
              type="text"
              style="position: absolute; right: -10px; top: -10px; padding: 0"
              ><i class="el-icon-circle-close"></i></el-button
          ></Upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="form.content"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumbs from "@/components/BreadCrumbs";
import Upload from "@/comp/Upload";
import { pick } from "lodash";

import { quillEditor } from "vue-quill-editor";
// 样式
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

const genDefaultForm = () => ({
  image: "",
  title: "",
  content: "",
  video: "",
  postId: "",
});
export default {
  data() {
    return {
      editorOption: {
        placeholder: "请输入内容...",
        theme: "snow",
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], // 加粗/斜体/下划线/删除线
              ["image"], // 图片、视频
              // [{ header: [1, 2, false] }],
              [{ list: "ordered" }, { list: "bullet" }],
              ["clean"],
            ],
          },
        },
      },
      dialog_visible: false,
      form: genDefaultForm(),
      file: {},
      rules: {
        channel: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
        title: [{ required: true, message: "请输入标题", trigger: "change" }],
        author: [{ required: true, message: "请输入来源", trigger: "change" }],
        content: [{ required: true, message: "请输入内容", trigger: "change" }],
        type: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
        url: [
          {
            message: "请选择图片",
            required: true,
            trigger: "change",
          },
        ],
      },
      list: [],
    };
  },
  components: {
    BreadCrumbs,
    Upload,
    quillEditor,
  },
  created() {
    this.getData();
  },
  methods: {
    replaceHtml(html) {
      // 去除标签和标签里的内容, <p><img src='...'>....</p>
      return html.replace(/<[^>]+>/g, "").trim();
    },
    async getData() {
      const { msg, data, code } = await this.$http.get("/diet/admin/post");
      if (code) return this.$message.error(msg);
      this.list = data.list;
    },
    async handleContent(item, edit = false) {
      this.form.postId = null;
      if (edit) {
        const obj = pick(item, Object.keys(this.form));
        Object.assign(this.form, obj);
      } else {
        this.form = genDefaultForm();
        // 重置表单校验
        this.$refs.ruleForm?.resetFields();
      }
      this.dialog_visible = true;
    },
    async delContent(item) {
      this.deleteMessageBox({
        message: "是否确认删除该条目？",
      }).then(async () => {
        const { code, msg } = await this.$http.delete(
          `/diet/admin/post/${item.postId}`
        );
        if (code) return this.$message.error(msg);
        await this.getData();
        this.$message.success(msg);
      });
    },
    deleteImg() {
      this.form.image = "";
    },
    deleteVideo() {
      this.form.video = "";
    },
    handleFileUpload(file) {
      const allowed_types = ["image/jpeg", "image/png"];
      const file_size = 1024 * 1024 * 15; // 后端校验的是30m，前端允许调整到最大30m
      if (!allowed_types.includes(file.raw.type)) {
        return this.$message.error("无效的文件类型。只允许 JPEG、PNG");
      }

      if (file.size > file_size) {
        return this.$message.error(
          `文件大小超过限制。最大允许 ${(file_size / (1024 * 1024)).toFixed(
            0
          )}M`
        );
      }
      this.form.image = file.response?.data.filepath;
    },
    handleFileUploadVideo(file) {
      const allowed_types = ["video/mp4", "video/quicktime"];
      const file_size = 1024 * 1024 * 15; // 后端校验的是30m，前端允许调整到最大30m
      if (!allowed_types.includes(file.raw.type)) {
        return this.$message.error("无效的文件类型。只允许 MP4、MOV");
      }

      if (file.size > file_size) {
        return this.$message.error(
          `文件大小超过限制。最大允许 ${(file_size / (1024 * 1024)).toFixed(
            0
          )}M`
        );
      }
      this.form.video = file.response?.data.filepath;
    },
    async onSubmit() {
      try {
        await this.$refs.ruleForm?.validate();
        const hasPostId = !!this.form.postId;

        const url = hasPostId
          ? `/diet/admin/post/${this.form.postId}`
          : "/diet/admin/post";

        const payload = {
          title: this.form.title,
          image: this.form.image,
          video: this.form.video,
          content: this.form.content,
          postId: this.form.postId,
        };
        console.log(payload);

        const method = hasPostId ? "patch" : "post";

        const { code, msg } = await this.$http[method](url, payload);
        if (code) return this.$message.error(msg);
        this.dialog_visible = false;
        this.$message.success("添加成功");
        this.$refs.ruleForm?.resetFields();
        await this.getData();
      } catch (error) {
        this.$message.error("请正确填写信息");
      }
    },
  },
};
</script>

<style scoped lang="less">
.card-content {
  cursor: pointer;
  height: 100%;
  height: 250px;
}
::v-deep {
  .el-card__body {
    height: 100%;
    box-sizing: border-box;
  }
  .el-card {
    height: 100%;
    box-sizing: border-box;
  }
  .el-dialog {
    margin-top: 4vh !important;
  }
  .el-image__inner {
    object-fit: cover;
  }
}
img {
  width: 100%;
  max-height: 200px;
}

.scrollable-content {
  overflow-y: auto; /* 仅纵向滚动 */
  overflow-x: hidden; /* 隐藏横向滚动 */
  word-break: break-word;
  // 超出 3 行省略号
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
